package com.pacific.sign.controller.user;

import com.pacific.common.request.CommonRequest;
import com.pacific.common.response.CommonResponse;
import com.pacific.sign.BaseController;
import com.pacific.sign.WebConstant;
import com.pacific.sign.biz.service.HcMenuService;
import com.pacific.sign.biz.user.service.UserService;
import com.pacific.sign.common.utils.MD5;
import com.pacific.sign.model.po.oaSchema.view.OdePartmentVo;
import com.pacific.sign.model.po.oaSchema.view.UserInfo;
import com.pacific.sign.model.po.pac.request.PacHcMenuRequest;
import com.pacific.sign.model.po.pac.response.PacHcMenuResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.http.Header;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Description;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Controller
@Description("登录控制器")
public class LoginController extends BaseController {

    @Autowired
    private UserService userService;
    @Autowired
    private HcMenuService hcMenuService;

    @Description("程序启动跳转到登录页面")
    @RequestMapping(value = "index",method= RequestMethod.GET)
    public String index(HttpServletRequest request,HttpSession session, HttpServletResponse response){
        Integer userId = (Integer) request.getSession().getAttribute(WebConstant.CURRENT_LOGIN_USER_INFO);
        if (userId != null && userId > 0) {
            return "redirect:/homePage";
        }
        //cookie自动登录
        if(cookieHoldLogin(request, session)){
            return "redirect:/homePage";
        }

        cookieRememberPwd(request, session);


        return "login/login";
    }

    @Description("登录")
    @RequestMapping(value = "login",method= RequestMethod.POST)
    public String login(HttpServletRequest request, HttpServletResponse response, HttpSession session, Model model,
                        @RequestParam(value = "username",required = false) String username,
                        @RequestParam(value = "password",required = false) String password,
                        @RequestParam(value = "autoLogin",required = false) String autoLogin,
                        @RequestParam(value = "rememberPwd",required = false) String rememberPwd){
        String errorMsg = "";
        if (username.equals("请输入用户名") || StringUtils.isEmpty(username) || password.equals("请输入密码") || StringUtils.isEmpty(password)) {
            errorMsg = "用户名或密码不能为空!";
            model.addAttribute("errorMsg", errorMsg);
            return "login/login";
        }


        //#############################################################################################
        //超级管理员[用户名：admin,密码：任意]
        if("admin".equals(username)){
            /**
             * 加载菜单...
             */
            CommonRequest<PacHcMenuRequest> req = new CommonRequest<PacHcMenuRequest>();
            PacHcMenuRequest pacHcMenuRequest = new PacHcMenuRequest();
            pacHcMenuRequest.setCode("0000");
            req.setRequestParam(pacHcMenuRequest);
            CommonResponse<PacHcMenuResponse> resp = hcMenuService.queryMenu(req);
            if(resp.isSuccess()){
                session.setAttribute(WebConstant.MENU_LIST_HTML, resp.getResult().getHtmlStr());
                session.setAttribute(WebConstant.ROLE_LIST_HTML, resp.getResult().getRoleStr());
            }
            session.setAttribute(WebConstant.CURRENT_LOGIN_USER_INFO, 1);

            UserInfo admin = new UserInfo();
            admin.setOaCode(1);
            admin.setName("超级管理员");
            admin.setJobcode("0000");
            session.setAttribute(WebConstant.LOGIN_USER, admin);//admin信息

            return "redirect:/homePage";
        }
        //#############################################################################################




        UserInfo userInfo = userService.login(username);
        byte [] inputPasswordhash = MD5.stringDecimalDigest(password).getBytes();
        if (null == userInfo) {
            errorMsg = "用户名不存在!";
            model.addAttribute("errorMsg", errorMsg);
            return "login/login";
        }
        if (!Arrays.equals(inputPasswordhash, userInfo.getPassword())) {
            errorMsg = "密码错误!";
        }


        if (autoLogin(autoLogin)) {
            //保持登录，密码保持加密后密码
            Cookie holdCookie = new Cookie(WebConstant.COOKIE_LOGIN_INFO, username +"-"+MD5.stringDecimalDigest(password));
            holdCookie.setPath("/");
            holdCookie.setMaxAge(60*60*24*7); 	   //password 保存7天
            response.addCookie(holdCookie);
        }
        if(autoLogin(rememberPwd)){
            //cookie记住密码
            Cookie rememberCookie = new Cookie(WebConstant.REMEMBER_PWD, username + "-" + password);
            rememberCookie.setMaxAge(60*60*24*7); //userInfo 保存7天
            rememberCookie.setPath("/");
            response.addCookie(rememberCookie);
        }

        if (StringUtils.isNotEmpty(errorMsg)) {
            model.addAttribute("errorMsg", errorMsg);
            return "login/login";
        }
        session.setAttribute(WebConstant.CURRENT_LOGIN_USER_INFO, userInfo.getOaCode());
        if(userInfo != null){
            userInfo.setJobcode(userInfo.getJobcode().substring(userInfo.getJobcode().length() - 4 , userInfo.getJobcode().length()));
        }
        session.setAttribute(WebConstant.LOGIN_USER, userInfo);//user信息


        /**
         * 加载菜单...
         */
        //校验是不是事业部
        boolean isBusiness = checkBusiness(userInfo.getDepCode());

        CommonRequest<PacHcMenuRequest> req = new CommonRequest<PacHcMenuRequest>();
        PacHcMenuRequest pacHcMenuRequest = new PacHcMenuRequest();
        pacHcMenuRequest.setCode(userInfo.getJobcode());
        pacHcMenuRequest.setBusiness(isBusiness);//是否为事业部
        req.setRequestParam(pacHcMenuRequest);
        CommonResponse<PacHcMenuResponse> resp = hcMenuService.queryMenu(req);
        if(resp.isSuccess()){
            session.setAttribute(WebConstant.MENU_LIST_HTML, resp.getResult().getHtmlStr());
            session.setAttribute(WebConstant.ROLE_LIST_HTML, resp.getResult().getRoleStr());
        }

        return "redirect:/homePage";
    }

    private boolean autoLogin(String autoLoginStr){
        return !StringUtils.isEmpty(autoLoginStr) && 2 == NumberUtils.toInt(autoLoginStr);
    }


    @Description("登陆成功后跳转页面")
    @RequestMapping(value = "homePage",method= RequestMethod.GET)
    public String homePage(HttpServletRequest request, HttpServletResponse response){
        request.setAttribute("dispatchUrl","http://www.baidu.com");
        return "testIndex";
    }

    @Description("登出")
    @RequestMapping(value = "logout",method= RequestMethod.GET)
    public String logout(HttpServletRequest request, HttpServletResponse response){
        request.getSession().removeAttribute(WebConstant.CURRENT_LOGIN_USER_INFO);

        //删除cookie
        Cookie pwdCookie = new Cookie(WebConstant.COOKIE_LOGIN_INFO, null);
        pwdCookie.setPath("/");
        pwdCookie.setMaxAge(0);
        response.addCookie(pwdCookie);

        return "redirect:/index";
    }

    @RequestMapping(value = "main",method= RequestMethod.GET)
    public String mainPage(){
        return "main";
    }


    /**
     * 校验是否为事业部
     */
    private boolean checkBusiness(String depCode){
        boolean isBusiness = false;
        OdePartmentVo odePartmentVo = userService.queryDepartment(depCode);
        if(odePartmentVo != null){
            int index = odePartmentVo.getTitle().indexOf("事业部");
            if(index != -1){
                isBusiness = true;
            }
        }
        return isBusiness;
    }




    /**
     * ######cookie自动登录
     */
    private boolean cookieHoldLogin(HttpServletRequest request, HttpSession session){
        Cookie[] cookies = request.getCookies();
        String cookieStr = "";
        if(cookies != null && cookies.length > 0){
            for(Cookie c :cookies ){
                if(WebConstant.COOKIE_LOGIN_INFO.equals(c.getName())){
                    cookieStr = c.getValue();
                }
            }
        }
        //存在cookie
        if(StringUtils.isBlank(cookieStr)){
            return  false;
        }
        String[] userInfoStrs = cookieStr.split("-");


        //#############################################################################################
        //超级管理员[用户名：admin,密码：任意]
        if("admin".equals(userInfoStrs[0])){
            /**
             * 加载菜单...
             */
            CommonRequest<PacHcMenuRequest> req = new CommonRequest<PacHcMenuRequest>();
            PacHcMenuRequest pacHcMenuRequest = new PacHcMenuRequest();
            pacHcMenuRequest.setCode("0000");
            req.setRequestParam(pacHcMenuRequest);
            CommonResponse<PacHcMenuResponse> resp = hcMenuService.queryMenu(req);
            if(resp.isSuccess()){
                session.setAttribute(WebConstant.MENU_LIST_HTML, resp.getResult().getHtmlStr());
                session.setAttribute(WebConstant.ROLE_LIST_HTML, resp.getResult().getRoleStr());
            }
            session.setAttribute(WebConstant.CURRENT_LOGIN_USER_INFO, 1);


            UserInfo admin = new UserInfo();
            admin.setOaCode(1);
            admin.setName("超级管理员");
            admin.setJobcode("0000");
            session.setAttribute(WebConstant.LOGIN_USER, admin);//admin信息

            return true;
        }
        //#############################################################################################


        UserInfo userInfo = userService.login(userInfoStrs[0]);
        byte [] inputPasswordhash = userInfoStrs[1].getBytes();
        if (Arrays.equals(inputPasswordhash, userInfo.getPassword())) {

            session.setAttribute(WebConstant.CURRENT_LOGIN_USER_INFO, userInfo.getOaCode());
            if(userInfo != null){
                userInfo.setJobcode(userInfo.getJobcode().substring(userInfo.getJobcode().length() - 4 , userInfo.getJobcode().length()));
            }
            session.setAttribute(WebConstant.LOGIN_USER, userInfo);//user信息


            /**
             * 加载菜单...
             */
            //校验是不是事业部
            boolean isBusiness = checkBusiness(userInfo.getDepCode());

            CommonRequest<PacHcMenuRequest> req = new CommonRequest<PacHcMenuRequest>();
            PacHcMenuRequest pacHcMenuRequest = new PacHcMenuRequest();
            pacHcMenuRequest.setCode(userInfo.getJobcode());
            pacHcMenuRequest.setBusiness(isBusiness);//是否为事业部
            req.setRequestParam(pacHcMenuRequest);
            CommonResponse<PacHcMenuResponse> resp = hcMenuService.queryMenu(req);
            if(resp.isSuccess()){
                session.setAttribute(WebConstant.MENU_LIST_HTML, resp.getResult().getHtmlStr());
                session.setAttribute(WebConstant.ROLE_LIST_HTML, resp.getResult().getRoleStr());
            }
            return true;
        }
        return false;
    }

    /**
     * 记住密码
     */
    private void cookieRememberPwd(HttpServletRequest request, HttpSession session){
        Cookie[] cookies = request.getCookies();
        String cookieStr = "";
        if(cookies != null && cookies.length > 0){
            for(Cookie c :cookies ){
                if(WebConstant.REMEMBER_PWD.equals(c.getName())){
                    cookieStr = c.getValue();
                }
            }
        }
        //存在cookie
        if(!StringUtils.isBlank(cookieStr)){
            String[] cookieStrs = cookieStr.split("-");
            session.setAttribute(WebConstant.COOKIE_LOGIN_USER_NAME, cookieStrs[0]);//用户名
            session.setAttribute(WebConstant.COOKIE_LOGIN_USER_PWD, cookieStrs[1]);//密码(明文)
        }
    }

}
